/*
 * @Description: 
 * @Version: 2.0
 * @Autor: echo
 * @Date: 2020-12-11 15:49:49
 * @LastEditors: lxc
 * @LastEditTime: 2020-12-24 15:03:15
 */
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser')
const passport = require('passport');

// 引入路由user.js
const users = require('./routes/api/users');
const classify = require('./routes/api/classify');
const orders = require('./routes/api/orders');

// DB config 
const db = require('./config/keys').mongoURI;

// Connect to mongodb
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true }).then((res) => {
    console.log('mongoConnectSuccess');
}).catch((err) => console.log('mongoerr', err))


// 使用中间件实现允许跨域
// app.use((req, res, next) => {
//     res.header("Access-Control-Allow-Origin", '*');
//     res.header("Access-Control-Allow-Headers", 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
//     res.header("Access-Control-Allow-Methods", 'PUT,POST,GET,DELETE,OPTIONS');
//     res.header("X-Powered-By", ' 3.2.1')
//     res.header("Content-Type", "application/json;charset=utf-8");
//     next();
// })
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
// passport初始化
app.use(passport.initialize());

// 将passport传入这个页面(passport);
require("./config/passport")(passport);

// app.get('/', (req, res) => {
//     res.send('hello word')
// });
// 使用body-parser中间件
app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json())
// 使用routes
app.use('/api/users', users);
app.use('/api/classify', classify);
app.use('/api/orders', orders);

const port = process.env.PORT || 5000;

app.listen(port, () => {
    console.log(`Server running on port ${port}`)
});